﻿using System.Reflection;
using System.Runtime.CompilerServices;

namespace Utils
{
    public class StaticClassUtil
    {
        #region 初始化静态类
        /// <summary>
        /// 初始化静态类
        /// </summary>
        /// <param name="serviceAssembly">服务程序集</param>
        public static async Task InitStaticClasses(Assembly serviceAssembly)
        {
            Type[] typeArr = serviceAssembly.GetTypes();

            await Parallel.ForEachAsync(typeArr, async (type, c) =>
            {
                if (type.GetCustomAttribute<StaticClassAttribute>() != null)
                {
                    try
                    {
                        RuntimeHelpers.RunClassConstructor(type.TypeHandle);
                        LogUtil.Info($"初始化静态类 {type.FullName} 成功");
                        await Task.CompletedTask;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"初始化静态类 {type.FullName} 失败：{ex}");
                        LogUtil.Error(ex, $"初始化静态类 {type.FullName} 失败");
                    }
                }
            });
        }
        #endregion

    }
}
